<?php
namespace Wx\Controller;

use Think\Controller;
use Think\Model;
class CouponController extends BaseController {
    public function _initialize()
    {
        parent::isLogin();
    }
    //领取优惠卷
 /*   public function getCoupon(){
        $time=time();
        $uid=session('oto_userId');
        $sql="SELECT y.id,y.deal_cate_id,s.shopName,y.deal_cate_id,y.good_id,y.supplier_id,y.shop_cat_id,y.brand_id,y.name,y.youhui_scope,y.good_id,y.supplier_id,y.begin_time,y.end_time,y.youhui_type,y.total_fee,y.breaks_menoy,y.deal_cate_id,y.expire_day,y.city_id FROM `oto_youhui` as y  left join oto_shops as s on y.supplier_id=s.shopId where $time between begin_time and end_time  and y.id not in(select youhui_id from oto_youhui_user_link where user_id=$uid)";
        $mayReceive=M()->query($sql);
        $codition='';
        foreach ($mayReceive as $k=>$v){
            switch($v['youhui_scope']){
                case 1:$codition='全部商品';break;
                case 2:$codition=$v['shopName'];break;
                case 3:$codition=$v['shopName'].'部分商品';break;
                case 4:$codition=$v['shopName'].'指定品牌';break;
                case 5:$codition=M('goods_cats')->where(array('catId'=>$v['deal_cate_id']))->getField('catName');break;
            }
            $mayReceive[$k]['condition']=$codition;
        }
        $this->mayReceive=$mayReceive;
        $this->display();
    }
    //领取优惠卷处理
    public function getCouponHandel(){
        if (!session('oto_userId')) {
         $this->ajaxReturn(array('status'=>-1));
            return;
        }
     
        if(IS_AJAX){
            $id=I('id');
            $uinfo=M('youhui_user_link')->where(array('youhui_id'=>$id,'user_id'=>session('oto_userId')))->find();
            $couponInfo=M('youhui')->where(array('id'=>$id))->find();
            if($uinfo){
                if($uinfo['todayget']>=$couponInfo['user_limit']){
                    $this->ajaxReturn(array('status'=>-3));
                    return;
                }
            }
            if($couponInfo['begin_time']<time()&&$couponInfo['end_time']>time()){
                if($uinfo){
                    $A=M('youhui_user_link')->where(array('youhui_id'=>$id))->setInc('surplus',1);
                    $B=M('youhui_user_link')->where(array('youhui_id'=>$id))->setInc('todayget',1);
                    if($A&&$B){
                        $this->ajaxReturn(array('status'=>0));
                    }else{
                        $this->ajaxReturn(array('status'=>-1));
                    }
                }else{
                    $data['youhui_id']=$id;
                    $data['user_id']=session('oto_userId');
                    $data['surplus']=1;
                    $data['todayget']=1;
                    $data['u_is_effect']=1;
                    $data['get_time']=time();
                    $res=M('youhui_user_link')->add($data);
                    M('Youhui')->where(array('id'=>$id))->setInc('user_count');
                    if($res){
                        $this->ajaxReturn(array('status'=>0));
                    }else{
                        $this->ajaxReturn(array('status'=>-1));
                    }
                }
            }else{
                $this->ajaxReturn(array('status'=>-1));
            }
        }
    }*/
    
    // 优惠卷处理
    public function my_coupon(){
        //有多少优惠卷待使用

        $time=time();
        $user_id=session('oto_userId');
        //优惠券是否过期更新
        $sql="select * from `oto_youhui_user_link`,`oto_youhui` where oto_youhui_user_link.user_id='{$user_id}' and u_is_effect='1' and oto_youhui_user_link.youhui_id=oto_youhui.id";
        $yhq_info=M()->query($sql);

        if(!isset($yhq_info))
        {
            $yhq_info='';
        }
        else
        {
            $t1=strtotime(date('Y-m-d 00:00:00',$time));
            for($i=0;$i<count($yhq_info);$i++)
            {
                $youhui_id=$yhq_info[$i]['youhui_id'];
                if($yhq_info[$i]['end_time']<$time)
                {
                    $sql="update oto_youhui_user_link set u_is_effect='0' where user_id='{$user_id}' and youhui_id='{$youhui_id}'";
                    M()->query($sql);
                }
                if($yhq_info[$i]['get_time']<$t1)
                {
                    $sql="update oto_youhui_user_link set todayget='0' where user_id='{$user_id}' and youhui_id='{$youhui_id}'";
                    M()->query($sql);
                }
            }
        }


        //未使用
        $sql = "select * from `oto_youhui_user_link`,`oto_youhui` where oto_youhui_user_link.user_id='{$user_id}' and u_is_effect='1' and surplus>0 and oto_youhui_user_link.youhui_id=oto_youhui.id";
        $youhui = M()->query($sql);
        $youhui = !empty($youhui)?$this->updateCoupon($youhui):array();
        $this->notUse=$youhui;

        //print_r( $this->notUse);

        //总共有多少张可领取的
        $time=time();
        $uid=session('oto_userId');
/*        $sql="SELECT y.deal_cate_id,s.shopName,y.deal_cate_id,y.good_id,y.supplier_id,y.shop_cat_id,y.brand_id,y.name,y.youhui_scope,y.good_id,y.supplier_id,y.begin_time,y.end_time,y.youhui_type,y.total_fee,y.breaks_menoy,y.deal_cate_id,y.expire_day,y.city_id FROM `oto_youhui` as y  left join oto_shops as s on y.supplier_id=s.shopId where $time between begin_time and end_time  and y.id not in(select youhui_id from oto_youhui_user_link where user_id=$uid)";
        $mayReceive=M()->query($sql);
        $this->mayReceive=count($mayReceive);*/
        
        //过期没使用
        $field="y.icon,y.deal_cate_id,u.surplus,s.shopName,y.deal_cate_id,y.good_id,y.supplier_id,y.shop_cat_id,y.brand_id,y.name,y.youhui_scope,y.good_id,y.supplier_id,y.begin_time,y.end_time,y.youhui_type,y.total_fee,y.breaks_menoy,y.deal_cate_id,y.expire_day,y.city_id";
        $expireNoUse=M('youhui_user_link')->field($field)->join("as u  join oto_youhui as y on u.youhui_id=y.id and  $time not between begin_time and end_time left join oto_shops as s on s.shopId=y.supplier_id where y.id not in(select youhui_id from oto_youhui_use_record where userId=$uid) and u.user_id= $uid" )->select();
        $expireNoUse = isset($expireNoUse)?$this->updateCoupon($expireNoUse):array();
        $this->expireNoUse=$expireNoUse;


       //print_r($this->expireNoUse);exit;
        //已经使用
        $existsSql="SELECT y.icon,y.deal_cate_id, s.shopName, y.deal_cate_id, y.good_id, y.supplier_id, y.shop_cat_id, y.brand_id, y. name, y.youhui_scope, y.good_id, y.supplier_id, y.begin_time, y.end_time, y.youhui_type, y.total_fee, y.breaks_menoy, y.deal_cate_id, y.expire_day, y.city_id FROM `oto_youhui_use_record` AS u JOIN oto_youhui AS y ON u.youhui_id = y.id LEFT JOIN oto_shops AS s ON s.shopId = y.supplier_id WHERE (u.userId = $uid)";
        $exisUse=M()->query($existsSql);
        $exisUse = isset($exisUse)?$this->updateCoupon($exisUse):array();
        //print_r($exisUse);exit;
        $this->exisUse=$exisUse;
        
        $this->display();
    }
    //现金券领取显示页
    public function coupon_center(){
        $db = D('Wx/Coupon');
        $db->overdue();//优惠券是否过期或领完

        $levelOne=M('goods_cats')->where(array('isShow'=>1,'catFlag'=>1,'parentId'=>0))->order('catSort ASC')->select();
        if(!empty($levelOne)){
            foreach ($levelOne as $key=>$value){
                $levelOne[$key]['list'] = $this->getCouponList($value['catId']);
            }
        }
        $this->assign('levelOne',$levelOne);
      //print_r($levelOne);exit;
        $this->display();
    }
    //根据店铺分类获取
    public function getCouponList($catID){
        $time = time();
        $where = "s.shopStatus=1 and s.shopFlag=1 and $time between begin_time and end_time and (s.goodsCatId1='$catID' or s.goodsCatId2='$catID' or s.goodsCatId1='$catID')";
        $count =  M('youhui')->join('as y join oto_shops s on  y.supplier_id=s.shopID')->where($where)->count();
        $Page   = new \Think\Page($count,10);
        $field  = 's.shopId,s.shopName,y.id,y.is_effect,y.supplier_id,y.shop_cat_id,y.youhui_scope,deal_cate_id,y.brand_id,y.begin_time,y.end_time,y.end_time as end_time2,y.breaks_menoy,y.name,y.total_num,y.user_count,y.icon,youhui_type,y.good_id';
        $list = M('youhui')->field($field)->join('as y join oto_shops s on  y.supplier_id=s.shopID')->where($where)->order('y.is_effect,shopID')->limit($Page->firstRow.','.$Page->listRows)->select();
        //echo M()->getlastsql()."<br />";
        $list = !empty($list)? $this->updateCoupon($list):array();
        //print_r($list);
        return $list;

    }

    //异步获取更多优惠券
    public function ajaxCouponList(){
        $catId = I('catId');
        $list  = $this->getCouponList($catId);
        if(!empty($list)){
            $this->ajaxReturn(array('error'=>'0','message'=>$list));
        }
        $this->ajaxReturn(array('error'=>'1','message'=>'not more'));
    }


    //优惠券明细字段更新
    public function updateCoupon($youhui=array()){
        for($i=0;$i<count($youhui);$i++)
        {
            if($youhui[$i]['youhui_type']==0){
                $youhui[$i]['breaks_menoy_msg']='￥'.$youhui[$i]['breaks_menoy'];
            }else{
                $youhui[$i]['breaks_menoy_msg']=(int)$youhui[$i]['breaks_menoy'].'折';
            }

            $youhui[$i]['begin_time']=date('Y.m.d',$youhui[$i]['begin_time']);
            $youhui[$i]['end_time']=date('Y.m.d',$youhui[$i]['end_time']);
            $shopId=$youhui[$i]['supplier_id'];
            $sql="select shopName,shopId,shopImg from `oto_shops` where shopId='{$shopId}'";
            $shops[$i]=M()->query($sql);
            if(isset($shops[$i]))
            {
                $youhui[$i]['shopName']=$shops[$i][0]['shopName'];
                $youhui[$i]['shopId']=$shops[$i][0]['shopId'];
                $youhui[$i]['shopImg']=$shops[$i][0]['shopImg'];
            }
            else
            {
                $youhui[$i]['shopName']="";
                $youhui[$i]['shopId']="";
                $youhui[$i]['shopImg']="";
            }
            if($youhui[$i]['youhui_scope']==1)
            {
                $youhui[$i]['msg']="全部商品";
            }
            if($youhui[$i]['youhui_scope']==2)
            {
                $shop_cat_id=$youhui[$i]['shop_cat_id'];
                $shop_cat_name="";
                $sql="select catName from `oto_shops_cats` where catId='{$shop_cat_id}'";
                $shop_cat[$i]=M()->query($sql);
                if(isset($shop_cat[$i]))
                {
                    $shop_cat_name=$shop_cat[$i][0]['catName'];
                }
                $youhui[$i]['msg']="店铺分类：".$shop_cat_name;
            }
            if($youhui[$i]['youhui_scope']==3)
            {
                $goods_id=$youhui[$i]['good_id'];
                $sql="select goodsName from `oto_goods` where goodsId='{$goods_id}'";
                $goods[$i]=M()->query($sql);
                if(isset($goods[$i]))
                {
                    $goodsName=$goods[$i][0]['goodsName'];
                }
                else $goodsName="";
                $youhui[$i]['msg']="商品：".$goodsName;
            }
            if($youhui[$i]['youhui_scope']==4)
            {
                $brand_id=$youhui[$i]['brand_id'];
                $brand_name="";
                $sql="select brandName from `oto_brands` where brandId='{$brand_id}'";
                $brand[$i]=M()->query($sql);
                if(isset($brand[$i]))
                {
                    $brand_name=$brand[$i][0]['brandName'];
                }
                $youhui[$i]['msg']="品牌：".$brand_name;
            }
            if($youhui[$i]['youhui_scope']==5)
            {
                $cat_name="";
                $cat_id=$youhui[$i]['deal_cate_id'];
                $sql="select catName from `oto_goods_cats` where catId='{$cat_id}'";
                $cat[$i]=M()->query($sql);
                if(isset($cat[$i]))
                {
                    $cat_name=$cat[$i][0]['catName'];
                }
                $youhui[$i]['msg']="商城分类：".$cat_name;
            }
        }

        return $youhui;
    }


    //领取优惠券处理
    public function getyouhuiid(){
        $id=(int)I('id');
        //$user_id=$_SESSION['oto_mall']['WST_USER']['userId'];
        $user_id=session('oto_userId');
        //未登录返回
        if (!$user_id) {echo json_encode(array('error'=>'-1','msg'=>'请先登录再领取优惠券','url'=>U('/Wx/Login/login')));die();}
        //判断是否已经领取过相同的优惠券
        $m=M('youhui_user_link');
        $where_user=array('youhui_id='.$id,'user_id='.$user_id);
        $find=$m->where($where_user)->find();
        $youhui=M('youhui')->where()->field('user_limit,supplier_id,total_num,user_count,is_effect')->find($id);
        //判断优惠券是否领完
        $sy=$youhui['total_num']-$youhui['user_count'];
        if ($sy<=0) {echo json_encode(array('error'=>'-2','msg'=>'该优惠券已经领完。'));die();}
        if ($youhui['is_effect']==0) {echo json_encode(array('error'=>'-3','msg'=>'该优惠券已经过期。'));die();}
        if ($find) {
            //时间判断
            if ($find['get_time']<strtotime('today')) {
                $find['todayget']=0;
            }
            //上限判断
            if ($find['todayget']>=$youhui['user_limit']) {
                echo json_encode(array('error'=>'-4','msg'=>'您已到达该优惠券的领取上限，请明天再试','ceiling'=>1));die();}
            //通过判断更新数据
            $find['surplus']=strval($find['surplus']+1);
            $find['get_time']=strval(time());
            $find['todayget']=strval($find['todayget']+1);
            $find['shop_id']=$youhui['supplier_id'];

            $result=$m->save($find);
            if (false !== $result) {
                M('Youhui')->where('id='.$id)->setInc('user_count');
                echo json_encode(array('error'=>'0','msg'=>'已成功领取优惠券！'));
            }else{
                echo json_encode(array('error'=>'-5','msg'=>'出错！请稍后再试'));
            }

        }else{
            //未领取过新增记录
            $data=array('youhui_id'=>$id,'user_id'=>(int)$user_id,'surplus'=>1,'get_time'=>time(),'shop_id'=>(int)$youhui['supplier_id'],'todayget'=>1,'u_is_effect'=>1);
            $add = $m->add($data);
            if ($add!==false) {
                M('Youhui')->where('id='.$id)->setInc('user_count');
                echo json_encode(array('error'=>'0','msg'=>'已成功领取优惠券！！'));
            }else{
                echo json_encode(array('error'=>'-5','msg'=>'出错！请稍后再试'));
            }
        }

    }


/*
    //获取用户优惠券页面内容
    public function getuserlist($type=1){
//        session('oto_userId',59);
        $userid=session('oto_userId');
//        $userid=$_SESSION['oto_mall']['WST_USER']['userId'];
        if ($type==2) {
            $m=M('youhui_use_record');
            //所需字段
            $field=array('oto_youhui.name,oto_youhui_use_record.*');
            //分页
            $where['userId']=$userid;
            $record=$m->join('oto_youhui ON oto_youhui_use_record.youhui_id = oto_youhui.id')->field($field)->limit($Page->firstRow.','.$Page->listRows)->order('oto_youhui_use_record.useTime desc')->where($where)->select();
            foreach ($record as $key => $vo) {
                $shopName=M('shops')->field('shopName')->find($vo['shopId']);
                $record[$key]['shopName']=$shopName['shopName'];
            }
            $data['ture']='ture';
            $data['list']=$record;
            return $data;
            die;
        }
        //ture则已过期内容
        if ($type==3) {
            $where['oto_youhui_user_link.u_is_effect']='0';
        }
        if ($type==1){
            $where['oto_youhui_user_link.u_is_effect']='1';
        }
        $m=M('youhui_user_link');
        $where['oto_youhui_user_link.user_id']=$userid;
        $where['oto_youhui_user_link.surplus']=array('GT',0);
        //分页

        //所需字段
        $field=array('oto_youhui.name,oto_youhui.breaks_menoy,oto_youhui.youhui_type,oto_youhui.supplier_id,oto_youhui.breaks_menoy,oto_youhui.total_fee,oto_youhui_user_link.*,oto_youhui.end_time,oto_youhui.begin_time,oto_youhui.youhui_scope,oto_youhui_user_link.u_is_effect,oto_youhui.is_effect');

        $data['list']=$m->join('oto_youhui ON oto_youhui_user_link.youhui_id = oto_youhui.id')->join('oto_users ON oto_youhui_user_link.user_id = oto_users.userId')->field($field)->where($where)->order('create_time desc')->select();


        //内容数组合并和处理
        for ($i=0; $i < count($data['list']); $i++) {
            $data['list'][$i]['supplier_name']=M('shops')->where('shopId='.$data['list'][$i]['supplier_id'])->field('shopName')->find();
            $data['list'][$i]['supplier_name']=$data['list'][$i]['supplier_name']['shopName'];
            $data['list'][$i]['id']=$data['list'][$i]['youhui_id'];
        }
        $data['user_id']=$userid;

        return $data;
    }*/
}